<script setup>
import * as api from "@/api/v-sys-service/exam"
import router from "@/router/index.js";
import {useRoute} from "vue-router";

const route = useRoute()

const isStart = ref(false)

const end = ref(false)

const examUserName = ref("")

const examId = route.query.examId

const paperId = ref("")

const examInfo = ref({
  examName: '',
  fullScore: '',
  passScore: '',
  questionTotal: '',
  carefulNotice: '',
})

const queType = ref({
  1: "单选题",
  2: "多选题",
  3: "判断题",
})

const queIndex = ref(0)

const paperContent = ref([])

const loading = ref({
  startExamLoading: false,
  answerQuestionLoading: false,
  submitPaperLoading: false,
})

const fillAnswer = computed(()=> {
  return () => {
    const item = paperContent.value[queIndex.value]
    const answers = item.answer
    const answer = answers && Array.isArray(answers) ? answers.join(",") : answers
    return [1, 2].includes(item.type) ? item.queContent.replace(/\（.*?\）/g,`(${answer})`) : item.queContent
  }
})

const numCard = computed(() => {
  return (item) => {
    return item.type === 2 ? ( Array.isArray(item.answer) && item.answer.length !== 0 ) : !!item.answer
  }
})

/**
 * 开始考试
 */
const startExam = async () => {

  const param = {
    examId: examId,
    examUserName: examUserName.value
  }
  loading.value.startExamLoading = true
  const { code, data } = await api.startExam(param)
  if (code === 200) {
    paperId.value = data.paperId

    await getExamById()
  }
  loading.value.startExamLoading = false
}

/**
 * 获取考题
 */
const getExamById = async () => {

  const { code, data } = await api.getExamById(examId)
  if (code === 200) {
    examInfo.value.examName = data.examName
    examInfo.value.fullScore = data.fullScore
    examInfo.value.passScore = data.passScore
    examInfo.value.questionTotal = data.questionTotal
    examInfo.value.carefulNotice = data.carefulNotice
    paperContent.value = JSON.parse(data.paperContent)
    paperContent.value = paperContent.value.map(ele => {
      ele.answer = ele.type ===  2 ? [] : ''
      return ele
    })
    isStart.value = true
  }
}

/**
 * 上一题
 */
const preQuestion = () => {
  queIndex.value > 0 && queIndex.value--
}

/**
 * 下一题
 */
const nextQuestion = () => {
  queIndex.value < paperContent.value.length -1 && queIndex.value++
}

/**
 * 跳转指定题
 */
const goQuestion = (index) => {
  queIndex.value = index
}

/**
 * 答题
 */
const answerQuestion = async () => {
  const que = paperContent.value[queIndex.value]
  const answer = !Array.isArray(que.answer) ? [que.answer] : que.answer
  if (answer.filter(ele => ele).length === 0) return ElMessage({message: '请填写答案', type: 'warning', duration: 800})
  const data = {
    examId: examId,
    paperId: paperId.value,
    queId: que.queId,
    submitResult: answer
  }
  loading.answerQuestionLoading = true
  const { code } = await api.answerQuestion(data)
  if (code === 200 && queIndex.value !== paperContent.value.length-1) {
    ElMessage({message: '下一题', type: 'success', duration: 800})
    goQuestion(++queIndex.value)
  }
  loading.answerQuestionLoading = false
}

/**
 * 交卷
 */
const submitPaper = async () => {
  // 最后一题自动提交答题
  await answerQuestion()
  const params = {
    examId: examId,
    paperId: paperId.value
  }
  loading.value.submitPaperLoading = true
  const { code } = await api.submitPaper(params)
  if (code === 200) {
    ElMessage({message: '操作成功', type: 'success', duration: 1000})
    end.value = true
  }
  loading.value.submitPaperLoading = false
}

const showResult = () => {
  const query = {
    examId: examId,
    paperId: paperId.value
  }
  router.push({path: '/exam-result', query})
}

const init = () => {

}

/**
 * 组件挂载后
 */
onMounted(() => {
  init()
})
</script>

<template>
  <div class="exam-box">
    <div class="start-exam" v-if="!isStart">
      <div style="margin-bottom: 50px">欢迎参加考试</div>
      <div class="flex">
        <el-input v-model="examUserName" placeholder="请输入考试人姓名" style="width: 230px;" />
        <el-button type="primary" @click="startExam" :loading="loading.startExamLoading">开始考试</el-button>
      </div>
    </div>
    <div class="exam-paper" v-if="isStart && !end">
      <div class="paper-title">
        <div class="exam-name flex justify-center">
          <div class="title flex-start">
            <span>{{ examInfo.examName }}</span>
          </div>
        </div>
        <div class="flex">
          <div class="title flex">
            <div style="width: 5em;white-space: nowrap;height: 100%">注意事项: &emsp;</div>
            <div>
              {{ examInfo.carefulNotice }}
            </div>
          </div>
        </div>
        <div class="flex align-center">
          <div class="title">
            共: <span>{{ examInfo.questionTotal }} 小题&ensp;</span>
          </div>
          <div class="title">
            满分: <span>{{ examInfo.fullScore }} 分&ensp;</span>
          </div>
          <div class="title">
            及格分: <span>{{ examInfo.passScore }} 分</span>
          </div>
        </div>
      </div>
      <div class="paper-content">
        <div class="que-card">
          <div class="que">
            <div class="type">{{queType[paperContent[queIndex].type]}}</div>
            <span>({{queIndex + 1}}/{{paperContent.length}})</span>
            <span>{{ fillAnswer() }}</span>
          </div>
          <div class="answer">
            <el-radio-group v-model="paperContent[queIndex].answer" v-if="[1, 3].includes(paperContent[queIndex].type)">
              <el-radio v-for="option in paperContent[queIndex].options" :label="`${option.tag}：${option.content}`" :value="option.tag"/>
            </el-radio-group>
            <el-checkbox-group v-model="paperContent[queIndex].answer" v-if="paperContent[queIndex].type === 2">
              <el-checkbox v-for="option in paperContent[queIndex].options" :label="`${option.tag}：${option.content}`" :value="option.tag" />
            </el-checkbox-group>
          </div>
        </div>
        <div class="que-btn flex justify-between">
          <div>
            <el-button size="small" @click="preQuestion" v-if="queIndex !== 0">上一题</el-button>
          </div>
          <div>
            <el-button size="small" @click="answerQuestion" :loading="loading.startExamLoading" v-if="queIndex !== paperContent.length -1">答题</el-button>
            <el-button size="small" @click="submitPaper" :loading="loading.submitPaperLoading" v-if="queIndex === paperContent.length -1">交卷</el-button>
          </div>
        </div>
      </div>
      <div class="number-card">
        <div class="num" v-for="(item,index) in paperContent"
             :class="{'num-success': numCard(item), 'num-primary': !numCard(item),
             'success-shadow': queIndex === index && numCard(item),
             'primary-shadow': queIndex === index && !numCard(item)}"
        >{{ index + 1 }}</div>
      </div>
    </div>
    <div class="end" v-if="end">
      <div class="thanks">考试完成,感谢参与</div>
      <div class="show" @click="showResult">点击查看考试结果</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.exam-box {
  .start-exam {
    max-width: 400px;
    height: 100%;
    min-width: 370px;
    padding: 150px 20px 20px;
    text-align: center;
    font-size: 30px;
  }
  .exam-paper {
    .paper-title {
      padding: 5px 10px 0;
      .exam-name {
        margin: 10px 0;
        .title {
          font-size: 17px;
          font-weight: bold;
        }
      }
      .title {
        font-weight: bold;
        font-size: 12px;
      }
    }
    .paper-content {
      padding: 10px;
      height: calc(100vh - 250px);
      .que-card {
        .que {
          color: #606266;
          font-size: 12px;
          .type {
            font-weight: bold;
          }
        }

      }
      .answer {
        :deep(.el-radio) {
          .el-radio__label {
            font-size: 12px;
          }
        }
        :deep(.el-checkbox) {
          .el-checkbox__label {
            font-size: 12px;
          }
        }
      }
      .que-btn {

      }
    }
    .number-card {
      display: flex;
      flex-wrap: wrap;
      padding: 0 10px;
      align-items: center;
      .num {
        height: 25px;
        width: 25px;
        margin: 3px;
        line-height: 25px;
        text-align: center;
        font-size: 12px;
        color: white;
        border-radius: 2px;
      }
      .num-primary {
        background-color: rgb(223, 224, 226);
      }
      .num-success {
        background-color: rgb(136, 209, 179);
      }
      .success-shadow {
        filter: drop-shadow(0px 3px 6px #88D1B3FF);
      }
      .primary-shadow {
        filter: drop-shadow(0px 3px 6px #DFE0E2FF);
      }
    }
  }
  .end {
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .thanks {
      color: #606266;
      font-size: 30px;
      text-align: center;
    }
    .show {
      cursor: pointer;
      font-size: 15px;
      color: #00a7ff;
      filter: drop-shadow(0px 3px 6px #00a7ff);
      text-align: center;
    }
  }
}
</style>
